package com.neusoft.clouduserfeign.controller;

import com.neusoft.clouduserfeign.dto.Result;
import com.neusoft.clouduserfeign.dto.User;
import com.neusoft.clouduserfeign.feign.UserServiceClient;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 链路跟踪测试控制器
 * 用于演示分布式链路跟踪功能
 */
@RestController
@RequestMapping("/tracing")
public class TracingTestController {

    @Autowired
    @Qualifier("com.neusoft.clouduserfeign.feign.UserServiceClient")
    private UserServiceClient userServiceClient;

    @Autowired
    private Tracer tracer;

    /**
     * 测试链路跟踪 - 获取用户列表
     */
    @GetMapping("/users")
    public Result<List<User>> testGetUsers() {
        Span span = tracer.nextSpan().name("feign-get-users").start();
        try {
            span.tag("operation", "get-users");
            span.tag("service", "feign-client");

            // 调用用户服务
            Result<List<User>> result = userServiceClient.getUserList(null, null, null);

            span.tag("result.code", String.valueOf(result.getCode()));
            span.tag("result.success", String.valueOf(result.isSuccess()));

            return result;
        } finally {
            span.end();
        }
    }

    /**
     * 测试链路跟踪 - 获取单个用户
     */
    @GetMapping("/users/{userId}")
    public Result<User> testGetUser(@PathVariable String userId) {
        Span span = tracer.nextSpan().name("feign-get-user").start();
        try {
            span.tag("operation", "get-user");
            span.tag("service", "feign-client");
            span.tag("user.id", userId);

            // 调用用户服务
            Result<User> result = userServiceClient.getUserByUserId(userId);

            span.tag("result.code", String.valueOf(result.getCode()));
            span.tag("result.success", String.valueOf(result.isSuccess()));

            return result;
        } finally {
            span.end();
        }
    }

    /**
     * 测试复杂链路跟踪 - 模拟业务流程
     */
    @GetMapping("/business/{userId}")
    public Result<String> testBusinessFlow(@PathVariable String userId) {
        Span span = tracer.nextSpan().name("business-flow").start();
        try {
            span.tag("operation", "business-flow");
            span.tag("service", "feign-client");
            span.tag("user.id", userId);

            // 步骤1：获取用户信息
            Span step1Span = tracer.nextSpan().name("step1-get-user").start();
            Result<User> userResult;
            try {
                step1Span.tag("step", "1");
                step1Span.tag("operation", "get-user");
                userResult = userServiceClient.getUserByUserId(userId);
                step1Span.tag("result.code", String.valueOf(userResult.getCode()));
            } finally {
                step1Span.end();
            }

            if (!userResult.isSuccess()) {
                span.tag("error", "user-not-found");
                return Result.error("用户不存在");
            }

            // 步骤2：获取用户列表（模拟其他业务逻辑）
            Span step2Span = tracer.nextSpan().name("step2-get-users").start();
            Result<List<User>> usersResult;
            try {
                step2Span.tag("step", "2");
                step2Span.tag("operation", "get-users");
                usersResult = userServiceClient.getUserList("user", "1", null);
                step2Span.tag("result.code", String.valueOf(usersResult.getCode()));
            } finally {
                step2Span.end();
            }

            // 步骤3：业务处理（模拟）
            Span step3Span = tracer.nextSpan().name("step3-business-logic").start();
            try {
                step3Span.tag("step", "3");
                step3Span.tag("operation", "business-logic");

                // 模拟业务处理时间
                Thread.sleep(100);

                step3Span.tag("processed", "true");
            } catch (InterruptedException e) {
                step3Span.tag("error", e.getMessage());
                Thread.currentThread().interrupt();
            } finally {
                step3Span.end();
            }

            span.tag("business.completed", "true");
            return Result.success("业务流程完成", "用户 " + userId + " 的业务流程已完成");

        } finally {
            span.end();
        }
    }
}
